package com.yoyosys.db.controller;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.yoyosys.db.DbService;
import com.yoyosys.db.partition.DBPartitionUtil;
import com.yoyosys.db.partition.vo.Message;
import com.yoyosys.db.partition.vo.PartitionInfo;
import com.yoyosys.db.partition.vo.SqlReq;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@Slf4j
@RestController
@RequestMapping("/dbtool")
public class DbController {
    @Value("${spring.datasource.url}")
    private String jdbcUrl;
    @Value("${spring.datasource.username}")
    private String username;
    @Value("${spring.datasource.password}")
    private String password;

    @Autowired
    private DbService dbService;

    /**
     * 执行查询
     *
     * @param sqlReq
     * @return
     */
    @PostMapping("/query")
    public Message query(@RequestBody SqlReq sqlReq) {
        return dbService.query(sqlReq);
    }

    /**
     * 执行更新
     *
     * @param sqlReq
     * @return
     */
    @PostMapping("/execute")
    public Message execute(@RequestBody SqlReq sqlReq) {
        return dbService.execute(sqlReq);
    }

    /**
     * 获取分区
     *
     * @param SqlReq
     * @return
     */
    public Message partition(@RequestBody SqlReq sqlReq) {
        Message message = new Message();
        try {
            log.info("partition: " + sqlReq.getSql() +" begin ...");
            long begin = System.currentTimeMillis();

            if (StrUtil.isNotBlank(sqlReq.getJdbcUrl())) {
                jdbcUrl = sqlReq.getJdbcUrl();
                username = sqlReq.getUsername();
                password = sqlReq.getPassword();
            }

            PartitionInfo partitionInfo = DBPartitionUtil.getPartition(sqlReq.getDbTypeEnum(),
                    jdbcUrl,
                    username,
                    password,
                    sqlReq.getSchemaName(), sqlReq.getTableName());
            long end = System.currentTimeMillis();
            long cost = end - begin;
            log.info("partition: " + sqlReq.getSql() +", totalCost(ms):" + cost);
            message.setCostTime(cost);
            message.setData(partitionInfo);
        } catch (Exception e){
            log.error("get partition error, SqlReq: " + sqlReq, e);
            message.setEndTime(DateUtil.format(new Date(), DatePattern.NORM_DATETIME_FORMAT));
        }
        return message;
    }
}
